package com.css.zfzx.sjcj.modules.qhdrilloverview.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.BeanUtil;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.LocationUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.repository.entity.QhDrillHistogramEntity;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.QhDrillOverviewNativeRepository;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.QhDrillOverviewRepository;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.entity.QhDrillOverviewEntity;
import com.css.zfzx.sjcj.modules.qhdrilloverview.service.QhDrillOverviewService;
import com.css.zfzx.sjcj.modules.qhdrilloverview.viewobjects.QhDrillOverviewQueryParams;
import com.css.zfzx.sjcj.modules.qhdrilloverview.viewobjects.QhDrillOverviewVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author aa
 * @date 2020-11-11
 */
@Slf4j
@Service
public class QhDrillOverviewServiceImpl implements QhDrillOverviewService {

	@Autowired
    private QhDrillOverviewRepository qhDrillOverviewRepository;
    @Autowired
    private QhDrillOverviewNativeRepository qhDrillOverviewNativeRepository;
//    private QhDrillOverviewEntity areaEntity;

    @Override
    public JSONObject queryQhDrillOverviews(QhDrillOverviewQueryParams queryParams, int curPage, int pageSize) {
        Page<QhDrillOverviewEntity> qhDrillOverviewPage = this.qhDrillOverviewNativeRepository.queryQhDrillOverviews(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhDrillOverviewPage);
        return jsonObject;
    }

    @Override
    public JSONObject queryQhDrillOverviews(QhDrillOverviewQueryParams queryParams) {
        List<QhDrillOverviewEntity> qhDrillOverviewList = this.qhDrillOverviewNativeRepository.listQhDrillOverviews(queryParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", qhDrillOverviewList);
        return jsonObject;
    }


    @Override
    public QhDrillOverviewEntity getQhDrillOverview(String id) {
        QhDrillOverviewEntity qhDrillOverview = this.qhDrillOverviewRepository.findById(id).orElse(null);
         return qhDrillOverview;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhDrillOverviewEntity saveQhDrillOverview(QhDrillOverviewEntity qhDrillOverview) {
        String uuid = UUIDGenerator.getUUID();
        qhDrillOverview.setId(uuid);
        qhDrillOverview.setCreateUser(PlatformSessionUtils.getUserId());
        qhDrillOverview.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhDrillOverview.setIsValid("1");
        qhDrillOverview.setReviewStatus("0");
        qhDrillOverview.setQualityinspectionStatus("0");
        this.qhDrillOverviewRepository.save(qhDrillOverview);
        return qhDrillOverview;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhDrillOverviewEntity updateQhDrillOverview(QhDrillOverviewEntity qhDrillOverview) {
        qhDrillOverview.setUpdateUser(PlatformSessionUtils.getUserId());
        qhDrillOverview.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = qhDrillOverview.getId();
        QhDrillOverviewEntity one = qhDrillOverviewRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(qhDrillOverview, one);
        this.qhDrillOverviewRepository.save(one);
        return qhDrillOverview;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhDrillOverviews(List<String> ids) {
        List<QhDrillOverviewEntity> qhDrillOverviewList = this.qhDrillOverviewRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhDrillOverviewList) && qhDrillOverviewList.size() > 0) {
            for(QhDrillOverviewEntity qhDrillOverview : qhDrillOverviewList) {
                //this.qhDrillOverviewRepository.delete(qhDrillOverview);
                qhDrillOverview.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillOverview.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillOverview.setIsValid("0");
                this.qhDrillOverviewRepository.save(qhDrillOverview);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhDrillOverview(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillOverviewEntity> qhDrillOverviewList = this.qhDrillOverviewRepository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhDrillOverviewList) && qhDrillOverviewList.size() > 0) {
            for(QhDrillOverviewEntity qhDrillOverview : qhDrillOverviewList) {
                qhDrillOverview.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillOverview.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillOverview.setReviewStatus("1");
                this.qhDrillOverviewRepository.save(qhDrillOverview);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            params.setTitleRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<QhDrillOverviewVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), QhDrillOverviewVO.class, params);
            List<QhDrillOverviewVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<QhDrillOverviewVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    QhDrillOverviewVO areaVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + areaVO.getRowNum() + "行" + areaVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public String exportExcel(QhDrillOverviewQueryParams queryParams, HttpServletResponse response) {
        List<QhDrillOverviewEntity> areaEntities = qhDrillOverviewNativeRepository.listQhDrillOverviews(queryParams);
        return this.exportExcel(areaEntities,response);
    }

    @Override
    public String exportExcel(String ids, HttpServletResponse response) {

        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillOverviewEntity> areaEntities = this.qhDrillOverviewRepository.findAllById(idList);

        return this.exportExcel(areaEntities,response);
    }

    @Override
    public String exportExcel(List<QhDrillOverviewEntity> entities, HttpServletResponse response) {
        try {
            // 深拷贝
            ArrayList<QhDrillOverviewVO> vos = new ArrayList<>();
            for (QhDrillOverviewEntity areaEntity : entities) {
                QhDrillOverviewVO vo = new QhDrillOverviewVO();
                BeanUtils.copyProperties(areaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "钻孔概况统计", "钻孔概况", QhDrillOverviewVO.class, "钻孔概况.xls", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private void saveExcel(List<QhDrillOverviewVO> list) {
        for (int i = 0; i < list.size(); i++) {
            //QhDrillOverviewEntity areaEntity = new QhDrillOverviewEntity();
            QhDrillOverviewVO areaVO = list.get(i);

            QhDrillOverviewEntity areaEntity = qhDrillOverviewRepository.findById(areaVO.getId()).get();
            // 将VO数据映射拷贝到库表中
            BeanUtil.copyPropertiesIgnoreNull(areaVO, areaEntity);

            // TODO 缺少终捡状态
            //修改状态
            areaEntity.setQualityinspectionStatus("2");

            updateQhDrillOverview(areaEntity);
        }
    }

    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }


    @Override
    public JSONObject checkCoordinate(String ids) {
        List<String> errorIds = new ArrayList<>();
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillOverviewEntity> qhDrillOverviewList = this.qhDrillOverviewRepository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhDrillOverviewList) && qhDrillOverviewList.size() > 0) {
            for(QhDrillOverviewEntity qhDrillOverview : qhDrillOverviewList) {
                double lon = qhDrillOverview.getLongitude();
                double lat = qhDrillOverview.getLatitude();
                String province = qhDrillOverview.getProvince();
                String city = qhDrillOverview.getCity();
                String area = qhDrillOverview.getArea();

                //校验
                if((lon > 180 || lon < -180) || (lat > 90 || lat < -90)) {
                    errorIds.add(qhDrillOverview.getId());
                    break;
                }

                Map<String, String> coordRes = LocationUtil.getLocationInfoByTD(lon,lat);

                if(!province.equals(coordRes.get("province")) ||
                        !city.equals(coordRes.get("city")) ||
                        !area.equals(coordRes.get("county"))) {
                    errorIds.add(qhDrillOverview.getId());
                }

            }
        }
        JSONObject json = new JSONObject();
        json.put("data",errorIds);
        if(errorIds.size() > 0) {
            json.put("message", "共" + errorIds.size() + "条数据校验未通过");
        } else {
            json.put("message", "数据校验通过");
        }
        return json;
    }

    private void setCheckFields(Map<String,String> methods){
        methods.put("drillCode", "钻孔编号");
        methods.put("drillDepth", "终孔深度");
        methods.put("longitude", "钻孔坐标经度值");
        methods.put("latitude", "钻孔坐标纬度值");
        methods.put("drillX", "钻孔坐标格网X值");
        methods.put("drillY", "钻孔坐标格网Y值");
        methods.put("stableWaterDepth", "稳定水位深度");
        methods.put("projectName", "勘察工程名称");
        methods.put("constructionInstitution", "勘察施工单位名称");
        methods.put("constructionPlace", "勘察施工地点");
        methods.put("siteClass", "场地分类");
        methods.put("province", "省");
        methods.put("city", "市");
        methods.put("area", "区/县");
    }

    @Override
    public JSONObject dataQualityCheck(List<QhDrillOverviewEntity> qhDrillOverviewList){
        JSONObject res = new JSONObject();

        try {
            if(!PlatformObjectUtils.isEmpty(qhDrillOverviewList) && qhDrillOverviewList.size() > 0) {
                for (QhDrillOverviewEntity qhDrillOverview : qhDrillOverviewList) {
                    //检查字段值不为空
                    StringBuilder errorMsg = new StringBuilder();
                    Map<String, String> methods = new HashMap<>();
                    setCheckFields(methods);

                    ServerUtil.checkFieldNull(qhDrillOverview, methods, errorMsg);

                    String strErrorMsg = errorMsg.toString();
                    if(!strErrorMsg.isEmpty()) {
                        qhDrillOverview.setQualityinspectionComments(strErrorMsg);
                        this.updateQhDrillOverview(qhDrillOverview);

                        res.put(qhDrillOverview.getId(),strErrorMsg);
                    }
                }
            }
        } catch (Exception e){
            log.error(e.getMessage());
        }

        return res;
    }

    @Override
    public JSONObject dataQualityCheck(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillOverviewEntity> qhDrillOverviewList = this.qhDrillOverviewRepository.findAllById(idList);

        return dataQualityCheck(qhDrillOverviewList);
    }
}
